package com.ftwj.service;

import com.ftwj.constant.ApiException;
import com.ftwj.dto.LoginResponse;
import com.ftwj.entity.SysUser;
import com.ftwj.mapper.SysUserManageMapper;
import com.ftwj.utils.result.MessageEnum;
import com.ftwj.utils.result.ResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;
import java.util.regex.Pattern;

@Service
public class SysUserManageAppService {

    @Autowired
    private SysUserManageMapper sysUserManageMapper;

    // 使用 BCrypt 进行密码加密
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();


    public void register(SysUser user) {
        // 检查用户是否已存在
        SysUser existingUser = sysUserManageMapper.findByPhoneNumber(user.getPhoneNumber());
        if (existingUser != null) {
            throw new ApiException("USER_ALREADY_EXISTS","用户已存在");
        }

        // 校验密码
        validatePassword(user.getPassword());
        validatePhoneNumber(user.getPhoneNumber());

        // 密码加密后再保存
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setId(UUID.randomUUID().toString()); // 生成唯一ID
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setState(0); // 将状态设置为待审核
        sysUserManageMapper.insertUser(user);
    }

    // 用户登录
    public ResultBean login(String phoneNumber, String password) {
        if (phoneNumber == null || phoneNumber.trim().isEmpty()) {
            return ResultBean.error(400, "手机号不能为空");
        }
        if (password == null || password.trim().isEmpty()) {
            return ResultBean.error(400, "密码不能为空");
        }

        SysUser user = sysUserManageMapper.findByPhoneNumber(phoneNumber);
        if (user == null || !user.getPassword().equals(password)) {
            return ResultBean.error(212, "手机号或密码错误");
        }
        if (user.getState() == 0) {
            return ResultBean.error(210, "用户尚未审核，请等待管理员审核通过后再尝试登录");
        } else if (user.getState() == 2) {
            return ResultBean.error(211, "用户审核未通过，无法登录");
        }

        user.setLoginDate(new Date());
        user.setLoginCount(user.getLoginCount() == null ? 1 : user.getLoginCount() + 1);
        sysUserManageMapper.updateUser(user);
        LoginResponse response = new LoginResponse("Login success", user.getId());
        return ResultBean.success(response);
    }

    // 根据用户ID查找用户
    public SysUser findUserById(String id) {
        return sysUserManageMapper.findById(id);
    }

    // 更新用户信息（包括状态）
    public void updateUser(SysUser user) {
        user.setUpdateTime(new Date());
        sysUserManageMapper.updateUser(user);
    }

    // 密码校验方法
    private void validatePassword(String password) {
        if (password.length() < 8) {
            throw new ApiException("PASSWORD_TOO_SHORT","密码长度必须大于8个字符");
        }

        String regex = "^(?=.*[A-Za-z])(?=.*\\d)(?=.*[@$!%*#?&])[A-Za-z\\d@$!%*#?&]+$";
        Pattern pattern = Pattern.compile(regex);
        if (!pattern.matcher(password).matches()) {
            throw new ApiException("PASSWORD_INVALID_FORMAT", "密码必须包含字母、数字和特殊字符");
        }
    }

    private void validatePhoneNumber(String phoneNumber) {
        if (phoneNumber == null || phoneNumber.trim().isEmpty()) {
            throw new RuntimeException("手机号不能为空");
        }

        // 使用正则表达式检查手机号格式
        String regex = "^1[3-9]\\d{9}$";
        Pattern pattern = Pattern.compile(regex);
        if (!pattern.matcher(phoneNumber).matches()) {
            throw new RuntimeException("手机号格式不正确");
        }
    }
}
